package cn.com.callback

import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
/**
 *
 * @Title: aipHSTGGdistribution
 * @Description:华盛证券  接收华盛“申请服顾” --外部接口
 * @author: chieh
 * @date 2022-10-26 10:28:00
 *
 */

public class aipHSTGGdistribution implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTGGdistribution.class);
    String custapiid = getProperty.get("custapiid");
    String custapikey = getProperty.get("custapikey");
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def apiid = inObject.getString("apiid");
            if(custapiid!=apiid){

                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(apiid不匹配),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }
            def timestamp = inObject.getString("timestamp");
            def sign = inObject.getString("sign");
            def apitype = inObject.getString("apitype");
            log.debug("解析信息-" + "apiid: " + apiid + "timestamp: " + timestamp + "	sign: " + sign + "	apitype: " + apitype);

            //  String apikey = "c5e5e59567162a6be0533228d50a17e9";
            String signfront = "apiid" + "=" + apiid + "&" + "apikey" + "=" + custapikey + "&" + "timestamp" + "=" + timestamp;
            log.debug("sign加密MD5前：" + signfront);

            String signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            if (!signafter.equals(sign)) {
                log.error("处理失败(sign签名错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(sign签名错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }

            outData = applyData(eliteBean, inObject, dataSourceID);

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("分配完成返回结果:" + outData);

        return outData;
    }

    // 处理申请任务
    public static String applyData(EliteBean eliteBean, JSONObject inObject, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdate = dateformat.format(System.currentTimeMillis());

        String uuid =KHUtil.getRandomString(36).toUpperCase();

        // 定义返回对象
        JSONObject resultJson = new JSONObject();

        try {

            JSONArray arrJsonArray = inObject.getJSONArray("data");
            int arrInt = arrJsonArray.size();
            log.debug("接入List数量:" + arrInt);

            String[] insertSQL = new String[arrInt*3];

            for (int i = 0; i < arrInt; i++) {

                JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);

                String username = KHUtil.FastJsonNull(arrSmsJson.getString("username"));//用户姓名
                String customerid = KHUtil.FastJsonNull(arrSmsJson.getString("customerid"));//华盛号
                String registerchannel = KHUtil.FastJsonNull(arrSmsJson.getString("registerchannel"));//注册渠道ID
                String latestchannel = KHUtil.FastJsonNull(arrSmsJson.getString("latestchannel"));//最新渠道信息ID 20240802调整新增字段

                // 后则作废不传了
                String registerattribution = KHUtil.FastJsonNull(arrSmsJson.getString("registerattribution"));//注册归因信息
                String accountchannel = KHUtil.FastJsonNull(arrSmsJson.getString("accountchannel"));//开户渠道信息
                String accountattribution = KHUtil.FastJsonNull(arrSmsJson.getString("accountattribution"));//开户归因信息

                log.debug("注册渠道ID:" + registerchannel+"   最新渠道信息ID:" + latestchannel);

                String deal_result = KHUtil.isNullMSG("username", username)  + KHUtil.isNullMSG("customerid", customerid);
                int deal_flag = KHUtil.isNull(deal_result) ? 0 : -1;

                def name1,name2="";
                def Parent1,Parent2="";
                def registerchannel2="";
                def latestchannel2="";
                //拼装
                if(registerchannel!=null&&registerchannel!=""){
                    //查询 注册渠道信息ID 的name
                    def name1List = eliteBean.chaxun_sql("select Code_Name from c_codetables  where 1=1 and use_type='渠道类型' and Code_id='"+registerchannel+"'", "dataSource");
                    if (name1List.size() > 0) {
                        name1 = name1List.get(0).get("Code_Name");
                    }
                    registerchannel2=registerchannel+" - "+name1;
                }
                if(latestchannel!=null&&latestchannel!=""){
                    //查询 最新渠道ID 的name
                    def name2List = eliteBean.chaxun_sql("select Code_Name,Parent1,Parent2 from c_codetables  where 1=1 and use_type='渠道类型' and Code_id='"+latestchannel+"'", "dataSource");
                    if (name2List.size() > 0) {
                        name2 = name2List.get(0).get("Code_Name");
                        Parent1 = name2List.get(0).get("Parent1");
                        Parent2 = name2List.get(0).get("Parent2");
                    }
                    latestchannel2=latestchannel+" - "+name2;
                }

                log.debug("注册渠道name:" + name1+"   最新渠道name:" + name2+"   一级渠道:" + Parent1+"   二级渠道:" + Parent2);

                //msg标题
                String title='服顾分配提醒--'+customerid;

                String content = "姓名 ："+ username + "<br />" + "\n华盛号 : " + customerid + "<br />" + "\n注册渠道信息 : " + registerchannel2 + "<br />" + "\n最新渠道 : " + latestchannel2 + "<br />" + "\n一级渠道: " + Parent1 + "<br />" + "\n二级渠道: " + Parent2;
                log.debug("内容拼接:" + content);
                insertSQL[i*3] = "INSERT INTO msg_notice(ID, SUBJECT, CATEGORYID, PRIORITY, RECEIVER, CREATEDBY, CREATEDTIME, DEPRECATEDTIME, MODIFIEDTIME, DELAYTIME, READCOUNT, REPLYCOUNT, STATUS, CONTENT) VALUES ('" + uuid + "', '" + title + "', '0B1BA53B-3C7F-E940-F0B8-63AED4FF4497', 1, '服务顾问;质培组;质培主管;服务顾问主管;', '000111', '" + createdate + "', NULL, NULL, '" + createdate + "', 0, 0, 0, '" + content + "')";
                //TEAM01 服务顾问 P38K33 质培组 NGRKM7 质培主管  JSHKD5 服务顾问主管
                insertSQL[i*3+1] = "INSERT INTO MSG_NOTICE_ROLEGROUP(MSGID, ROLEGROUPID) select '" + uuid + "', 'TEAM01' union select '" + uuid + "', 'P38K33' union select '" + uuid + "', 'NGRKM7' union select '" + uuid + "', 'JSHKD5'";

                //详情数据
                insertSQL[i*3+2] = "INSERT INTO hst_gwapply_msg_notice(username,customerid,registerchannel,latestchannel,registerattribution,accountchannel,accountattribution,createdate,deal_flag,deal_result) values('" + username + "','" + customerid + "','" + registerchannel + "','" + latestchannel + "','" + registerattribution + "','" + accountchannel + "','" + accountattribution + "',now(),'"+deal_flag+"','"+deal_result+"')";
            }

            // 处理批次信息
            String enddate = dateformat.format(System.currentTimeMillis());
            log.debug("提交数据库操作SQL集:" + insertSQL.toString());

            // 将数据插入数据库
            int[] sqlResult = eliteBean.updateBatch(insertSQL, dataSourceID);
            log.debug("提交数据库操作SQL结果:" + sqlResult.toString());



            // 生成处理完成时间
            endTime = System.currentTimeMillis();

            // 包装拼接返回JSONObject
            resultJson.put("resultcode", 1);
            resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        } catch (Exception e) {
            endTime = System.currentTimeMillis();
            resultJson.put("resultcode", 4);
            resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" +(endTime -startTime));

        }

        return resultJson.toString();
    }
}
